<?php

namespace app\api\controller;

use app\admin\model\Worktags;
use app\common\controller\Api;
use think\Db;


/**
 * 商品
 */
class Products extends Api
{
    protected $noNeedLogin = ['products_list'];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Products;
    }

    public function products_list()
    {
        $recommend = input('recommend'); // 首页推荐
        $type = input('type'); // 儿童或老年
        $tags = input('tags'); // 用逗号分隔的字符串，
        $name = input('name'); // 用逗号分隔的字符串，
        // 初始化查询
        $query = Db::name('products')->field('id, product_name, image, remarks, price');
        // 添加推荐条件
        $query->whereNull('deletetime');
        if ($recommend == 1) {
            $query->where('recommend', '=', $recommend);
        }
        // 类型条件0儿童 1老年人
        if ($type !== null && $type !== "") {
            $query->where('type', '=', $type);
        }

        if ($name !== null && $name !== "") {
            $query->where('product_name', 'like','%' .$name. '%');
        }

        // 根据标签查询
        if (!empty($tags)) {
            $idArray = explode(',', $tags);
            $tagConditions = [];
            foreach ($idArray as $id) {
                $id = trim($id);
                if ($id !== "") {
                    $tagConditions[] = "FIND_IN_SET('{$id}', tagid)";
                }
            }
            if (!empty($tagConditions)) {
                $query->whereRaw('(' . implode(' OR ', $tagConditions) . ')');
            }
        }
        // 使用 paginate 进行分页
        $list = $query->order('id desc')->paginate(10);
        $this->success('请求成功',  $list->toArray());

    }

    /*
     * 标签
     */
    public function tags(){

       $list= Worktags::where('type','=', input('type'))->select();
        $this->success('请求成功', $list);
    }

    /*
     * 商品详情
     */
    public function products_info()
    {
        if (!$id = input('id')) {
            $this->error('请选择商品');
        }
        $info = $this->model->field('id,image,carousel,rich_text,price,remarks,product_name')->where('id', $id)->find();
        if($info){
            $info['carousel']= explode(',', $info['carousel']);
        }
        $this->success('请求成功', $info);
    }
}
